package com.yuqing.myblogServe.security;

import cn.hutool.json.JSONUtil;
import com.yuqing.myblogServe.common.lang.Result;
import com.yuqing.myblogServe.dao.entity.SysUser;
import com.yuqing.myblogServe.dao.entity.Token;
import com.yuqing.myblogServe.service.SysRoleService;
import com.yuqing.myblogServe.service.SysUserService;
import com.yuqing.myblogServe.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {
    @Autowired
    JwtUtils jwtUtils;
    @Autowired
    SysUserService sysUserService;
    @Autowired
    SysRoleService sysRoleService;


    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        response.setContentType("application/json;charset=UTF-8");
        ServletOutputStream outputStream = response.getOutputStream();

        // 生成jwt返回
        String jwt = jwtUtils.generateToken(authentication.getName());
        response.setHeader(jwtUtils.getHeader(), jwt);
        Token token = new Token();
        token.setToken(jwt);
        SysUser user = sysUserService.getByUsername(authentication.getName());
        token.setSysUser(user);
        Result result = Result.succ(token);
        outputStream.write(JSONUtil.toJsonStr(result).getBytes("UTF-8"));
        outputStream.flush();
        outputStream.close();
    }
}
